package com.sskj.wallet.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.fingerprints.service.IFingerprintClient;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.RxSchedulersHelper;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinEnum;
import com.sskj.lib.bean.SelfCoinBean;
import com.sskj.lib.bean.WalletBean;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.SelfCoinBeanViewModel;
import com.sskj.lib.model.room.WalletBeanViewModel;
import com.sskj.lib.mvchelper.ModelRx2DataSource;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.lib.util.WalletUtil;
import com.sskj.wallet.R;
import com.sskj.wallet.R2;
import com.sskj.wallet.bean.BalanceBean;
import com.sskj.wallet.bean.BannerBean;
import com.sskj.wallet.bean.CoinAssetBean;
import com.sskj.wallet.bean.EthBalanceBean;
import com.sskj.wallet.bean.NoticeBean;
import com.sskj.wallet.component.DaggerUserDataComponent;
import com.sskj.wallet.presenter.WalletFragmentPresenter;
import com.sskj.wallet.uitl.TipWalletUtil;
import com.sskj.wallet.widget.TopMenuPop;
import com.zaaach.toprightmenu.MenuItem;
import com.zaaach.toprightmenu.TopRightMenu;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.WALLET_MAIN)
public class WalletFragment extends BaseFragment<WalletFragmentPresenter> {
    @BindView(R2.id.ivMsg)
    ImageView ivMsg;
    @BindView(R2.id.ivMenu)
    ImageView ivMenu;
    @BindView(R2.id.ivSee)
    ImageView ivSee;
    @BindView(R2.id.tvRMB)
    TextView tvRMB;
    @BindView(R2.id.tvUSDT)
    TextView tvUSDT;
    @BindView(R2.id.ivNotice)
    ImageView ivNotice;
    @BindView(R2.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R2.id.tvMore)
    ImageView tvMore;
    @BindView(R2.id.llNotice)
    LinearLayout llNotice;
    @BindView(R2.id.llAdd)
    LinearLayout llAdd;
    @BindView(R2.id.llWalletBg)
    LinearLayout llWalletBg;
    @BindView(R2.id.llChange)
    LinearLayout llChange;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.tvWalletName)
    TextView tvWalletName;
    @BindView(R2.id.tvMsg)
    TextView tvMsg;
    @BindView(R2.id.btBackup)
    Button btBackup;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private Disposable noticeDispo;
    private List<SelfCoinBean> selfCoinBeans = new ArrayList<>();//当前筛选币种
    private List<SelfCoinBean> selfCoinBeanEths = new ArrayList<>();//ETH自选币
    @Inject
    SelfCoinBeanViewModel selfCoinBeanViewModel;
    @Inject
    WalletBeanViewModel walletBeanViewModel;
    private WalletBean walletBeanBtc;
    private WalletBean walletBeanEth;
    private WalletBean walletBean;
    private String balance;
    private boolean isSee = true;
    private SlimAdapter slimAdapter;
    private BannerBean noticeList;
    private String usdt;

    @Override
    protected int getLayoutId() {
        return R.layout.wallet_fragment_main;
    }

    @Override
    public WalletFragmentPresenter getPresenter() {
        return new WalletFragmentPresenter();
    }

    @Override
    protected void initView() {
        DaggerUserDataComponent.create().inject(this);
        RxBus.getDefault().register(this);
        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 28);
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.wallet_0a1));
            return textView;
        });
        selfCoinBeanViewModel.getUsers().observe(this, selfCoinBeans1 -> {
            if (selfCoinBeans1 != null) {
                selfCoinBeanEths = selfCoinBeans1;
            } else {
                selfCoinBeanEths.clear();
            }
            mPresenter.refresh();
        });
        walletBeanViewModel.getUsers().observe(this, walletBeans -> {
            if (walletBeans != null) {
                if (walletBeans.get(0).getCode().equals(CoinEnum.BTC.getCode())) {
                    walletBeanBtc = walletBeans.get(0);
                    walletBeanEth = walletBeans.get(1);

                } else {
                    walletBeanBtc = walletBeans.get(1);
                    walletBeanEth = walletBeans.get(0);
                }
                mPresenter.setAddr(walletBeanEth.getAddr());
                if (WalletUtil.walletBean == null) {
                    walletBean = walletBeanBtc;
                } else {
                    if (WalletUtil.walletBean.getCode().equals(CoinEnum.BTC.getCode())) {
                        walletBean = walletBeanBtc;
                    } else {
                        walletBean = walletBeanEth;
                    }
                }
                updateUI();
            }
        });

        LiveDataBus.get().with(RxBusCode.CHANGE_WALLET, CoinEnum.class)
                .observe(getActivity(), coinEnum -> {
                    if (llAdd == null)
                        return;
                    if (coinEnum == CoinEnum.BTC) {
                        selfCoinBeans.clear();
                        walletBean = walletBeanBtc;
                        selfCoinBeans.add(new SelfCoinBean(CoinEnum.BTC.getCode()));
                        selfCoinBeans.add(new SelfCoinBean(CoinEnum.USDT.getCode()));
                        llAdd.setVisibility(View.INVISIBLE);
                        tvWalletName.setText("BTC-wallet");
                        llWalletBg.setBackground(ContextCompat.getDrawable(App.INSTANCE, R.mipmap.lib_bg_main_btc));
                    } else {
                        selfCoinBeans.clear();
                        llAdd.setVisibility(View.VISIBLE);
                        walletBean = walletBeanEth;
                        selfCoinBeans.addAll(selfCoinBeanEths);
                        tvWalletName.setText("ETH-wallet");
                        llWalletBg.setBackground(ContextCompat.getDrawable(App.INSTANCE, R.mipmap.lib_bg_main));
                    }
                    updateUI();
                    mPresenter.refresh();
                });
        initRecy();
        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                mPresenter.refresh();
            }
        });
    }

    private void updateUI() {
        if (walletBean == null || btBackup == null)
            return;
        btBackup.setVisibility(walletBean.isBackup() ? View.INVISIBLE : View.VISIBLE);
        ClickUtil.click(btBackup, () -> {
            ARouter.getInstance().build(RConfig.WALLET_WALLET_EDIT).withString(Constans.CODE, walletBean.getCode()).navigation();
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN, code = RxBusCode.WALLET_REFRESH)
    public void refresh() {
        updateUI();
        if (WalletUtil.walletBean.getCode().equals(CoinEnum.BTC.getCode())) {
            walletBean = walletBeanBtc;
        } else {
            walletBean = walletBeanEth;
        }
        mPresenter.refresh();
    }

    @Override
    protected void initData() {
        mPresenter.getBanner();
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getBanner();
        mPresenter.refresh();
    }

    @Override
    protected void initEvent() {
        ClickUtil.click(ivMsg, () -> {
            ARouter.getInstance().build(RConfig.MINE_NEWSLIST).navigation();
        });
        ClickUtil.click(ivMenu, () -> {

            TopMenuPop topMenuPop = new TopMenuPop(getActivity());
            View contentView = topMenuPop.getContentView();
            View llAddCoin = contentView.findViewById(R.id.llAddCoin);
//            if (WalletUtil.walletBean.getCode().equals(CoinEnum.BTC.getCode())) {
//                llAddCoin.setVisibility(View.GONE);
//            }
            llAddCoin.setVisibility(View.GONE);

            View llScan = contentView.findViewById(R.id.llScan);
            View llWalletManage = contentView.findViewById(R.id.llWalletManage);
            View llAddressBook = contentView.findViewById(R.id.llAddressBook);
            ClickUtil.click(llAddCoin, () -> {
                topMenuPop.dismiss();
                ARouter.getInstance().build(RConfig.WALLET_ADD_COIN).navigation();
            });
            ClickUtil.click(llScan, () -> {
                topMenuPop.dismiss();

                ARouter.getInstance().build(RConfig.LIB_SCAN).withBoolean(Constans.IS_SHOW,true).navigation();

            });
            ClickUtil.click(llWalletManage, () -> {
                topMenuPop.dismiss();

                ARouter.getInstance().build(RConfig.WALLET_WALLET_MANAGE).navigation();

            });
            ClickUtil.click(llAddressBook, () -> {
                topMenuPop.dismiss();

                ARouter.getInstance().build(RConfig.WALLET_ADDRESS_BOOK).navigation();
            });
            topMenuPop.showPopupWindow(ivMenu);
        });
        ClickUtil.click(llAdd, () -> {
            ARouter.getInstance().build(RConfig.WALLET_ADD_COIN).navigation();
        });
        ClickUtil.click(llChange, () -> {
            LiveDataBus.get().with(RxBusCode.DRAWER_OPEN, Integer.class).postValue(1);
        });
        ClickUtil.click(100, ivSee, () -> {
            isSee = !isSee;
            tvRMB.setText(isSee ? ("≈￥" + balance) : "****");
            tvUSDT.setText(isSee ? (usdt + " USDT") : "****");
            ivSee.setImageResource(isSee ? R.mipmap.lib_icon_see : R.mipmap.lib_icon_unsee);
        });
    }

    private void initRecy() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setLeftPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setRightPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.wallet_bdc))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.wallet_recy_item_wallet_main, new SlimInjector<CoinAssetBean>() {
            @Override
            public void onInject(CoinAssetBean data, IViewInjector injector, List payloads) {
                injector
                        .imageCircle(R.id.ivCoin, CoinEnum.getByCode(data.getCode()).getRes())
                        .text(R.id.tvCoin, data.getCode())
                        .text(R.id.tvUSDT, NumberUtil.keepNoZero(data.getPrice()))
                        .text(R.id.tvRMB, String.format("≈￥%s", CoinUtil.keepRMB(data.getCnyPrice())))
                        .text(R.id.tvMyUSDT, data.getAvailable())
                        .text(R.id.tvMyRMB, String.format("≈￥%s", CoinUtil.keepRMB(data.getCnyAvailable())));
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, i, view) -> {
                    CoinAssetBean dataItem = (CoinAssetBean) slimAdapter.getDataItem(i);
                    if (dataItem.getCode().equals(CoinEnum.ETH.getCode())) {
                        dataItem.setAddress(walletBeanEth.getAddr());
                    }
                    ARouter.getInstance().build(RConfig.WALLET_COIN_INFO)
                            .withString(Constans.ADDRESS, dataItem.getAddress())
                            .withString(Constans.CODE, dataItem.getCode())
                            .withSerializable(Constans.DATA, dataItem)
                            .navigation();
                });


    }

    public void updateNotice(List<BannerBean> notice) {
        if (tvNotice != null) {
            if (notice.size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                noticeList = notice.get((int) (i % notice.size()));
                                tvNotice.setText(noticeList.getTitle());
                                ClickUtil.click(tvNotice, () -> {
                                    ARouter.getInstance().build(RConfig.MINE_NEWS_DETAIL)
                                            .withString("id", noticeList.getId())
                                            .navigation();
                                });
                            }
                        }, System.out::println);
            }
        }
    }

    public void updateBalance(BalanceBean balanceBean) {
        refreshStop();
        balance = "0";
        usdt = "0";
        if (WalletUtil.walletBean.getCode().equals(CoinEnum.ETH.getCode())) {

            Flowable.fromIterable(selfCoinBeanEths)
                    .toList()
                    .subscribe((selfCoinBeans1, throwable) -> {
                        this.selfCoinBeans = selfCoinBeans1;
                    });
        }
        Flowable.fromIterable(selfCoinBeans)
                .map(selfCoinBean -> {
                    for (CoinAssetBean coinAssetBean : balanceBean.getCoinAssetBeans()) {
                        if (coinAssetBean.getCode().equals(selfCoinBean.getCode())) {
                            balance = new BigDecimal(balance).add(new BigDecimal(coinAssetBean.getCnyAvailable())).toPlainString();
                            usdt = new BigDecimal(usdt).add(new BigDecimal(coinAssetBean.getUsdt())).toPlainString();
                            return coinAssetBean;
                        }
                    }
                    CoinAssetBean coinAssetBean = new CoinAssetBean();
                    coinAssetBean.setCode(selfCoinBean.getCode());
                    return coinAssetBean;
                })
                .toList()
                .subscribe((coinAssetBeans, throwable) -> {
                    slimAdapter.updateData(coinAssetBeans);
                });
        balance = CoinUtil.keepRMB(balance);
        usdt = CoinUtil.keepUSDT(usdt);
        tvRMB.setText(("≈￥" + balance));
        tvUSDT.setText(usdt + " USDT");

    }

    public void refreshStop() {
        ((BaseActivity) (getActivity())).hideLoading();
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            Flowable.timer(1, TimeUnit.SECONDS)
                    .compose(RxSchedulersHelper.transformer())
                    .subscribe(aLong -> {
                        coolRefreshView.setRefreshing(false);
                    });
        }
    }

    public void updateMsg(int un_read) {
        if (un_read > 0) {
            tvMsg.setText(un_read + "");
            tvMsg.setVisibility(View.VISIBLE);
        } else {
            tvMsg.setText("");
            tvMsg.setVisibility(View.INVISIBLE);
        }
    }
}
